import pickle
import shelve
import os
class User:
    '''User class'''
    def __init__(self, name, password):
        self.Name = name
        self.Password = password

class Users:
    '''Users class. Represents collection of users.'''
    online = []
    users = []
    def __init__(self):
        self._loadusers()
        self._saveusers()
        
    def _saveusers(self):
        path = os.path.join("data", "users.dat")
        try:
            usersfile = file(path, "w")
        except IOError, error:
            print "Error saving users database " + path + "(" + error + ")"
            return
        pickle.dump(self.users, usersfile)

    def _loadusers(self):
        '''Load users database in memory'''
        try:
            self.users = pickle.load(file(os.path.join("data", "users.dat")))
            print "User database loaded!"
        except IOError:
            print "Error opening users database file. Creating user database..."

    def register(self,user):
        '''Add user to database'''
        self.users.append(user)
        self._saveusers()

    def kick(self, user):
        '''Kicks user offline'''
        self.online.remove(user)

    def login(self, user):
        '''Login user online'''
        self.online.append(user)

    def getonline(self, mode = "class"):
        '''Get array of online users'''
        if mode == "class":
            return self.online
        if mode == "array":
            b = []
            for a in self.online:
                b.append(a.Name)
            return b

    def delete(self,user):
        '''Remove user from database'''
        if user in self.users:
            self.users.remove(user)
            return 0
        else:
            return 1

    def search(self, name, where):
        '''Search for users in database by name.
        Pass 'all' as second argument to search whole database
        Pass 'online' to search users currently online'''
        if where == "all":
            tmp = self.users
        elif where == "online":
            tmp = self.online
        else:
            return 1
        for a in tmp:
            if a.Name == name:
                return a
        return 0
